<script>
import addtable from '@/mixins/addtable'
import AjaxStore from '@/utils/store/proxyAjax'
import store from './store'
import { getToken } from '@/utils/auth'

export default {
  name: 'model',
  mixins: [addtable, store],
  data () {
    return {
      tableOptWidth: '120',
      tableSelectionCol: false,
      idKey: 'id',
      delIdKey: 'id',
      modelUrl: '',
      acceptFileType: '.bpmn20.xml,.bpmn', // 接受导入的文件类型
      showInputFlag: true,
      file: '',
      inputPlaceholder: '输入模型名称搜索',
      store: new AjaxStore({
        url: '/v1/activiti/models/getList'
      }),
      addUrl: '/v1/activiti/models/newModel',
      exportUrl: '/v1/activiti/models/export',
      importUrl: '/v1/activiti/models/importModel',
      deploymentModelUrl: '/v1/activiti/models/deployment',
      delUrl: '/v1/activiti/models/delete',
      columns: [
        { prop: 'id', label: '模型编号', sortable: true, 'min-width': '110', 'show-overflow-tooltip': true, 'header-align': 'center', aligin: 'left' },
        { prop: 'name', label: '模型名称', sortable: true, 'min-width': '110', 'show-overflow-tooltip': true, 'header-align': 'center', aligin: 'left' },
        { prop: 'version', label: '版本', sortable: true, width: '110', 'show-overflow-tooltip': true, 'header-align': 'center', aligin: 'left' },
        { prop: 'createTime', label: '创建时间', sortable: true, width: '155', 'show-overflow-tooltip': true, 'header-align': 'center', aligin: 'left' }
      ],
      searchFields: [],
      searchModel: {},
      searchBtnList: [],
      toolPanelBtnList: this.toolPanelBtns,
      tableRowBtnList: this.tableRowBtnList
    }
  },
  methods: {
    handleInputClick(ev, val) {
      const params = {}
      params.q_name = val
      this.store._searchParams = params
      this.$refs.table.load(1, this.store.limit)
    },
    handleAdd() {
      return this.add()
        .then(({ success, data }) => {
          if (success) {
            const modelId = data.redirectUrl.split('=')[1]
            this.$router.push({
              path: `/activiti/model/drawModel/${modelId}`
            })
          } else {
            throw new Error('绘制流程失败！')
          }
        })
        .catch(err => console.log(err))
    },
    handleEdit(row) {
      this.$router.push({
        path: `/activiti/model/drawModel/${row.id}`
      })
    },
    // 导出
    handleExport(row) {
      this.export({ id: row.id })
      .then((res) => {
        if (!res.success) {
          let a = document.createElement('a')
          a.href = process.env.VUE_APP_API_URL + 'v1/activiti/models/export?id=' + row.id + '&token=' + getToken()
          a.download = ''
          a.click()
        }
      })
      .catch(err => console.log(err))
    },
    // 发布
    handleDeployment(row) {
      return this.deploymentModel({ id: row.id })
        .then(({ success, message }) => {
          this.$message({
            type: success ? 'success' : 'error',
            message
          })
          if (success) {
            this.$refs.table.load(1)
          }
        })
        .catch(err => console.log(err))
    },
    handleDelete(row) {
      return this.$confirm('此操作不能回退，确认要删除您选中的数据么?', '提示', {
        cancelButtonText: '取消',
        confirmButtonText: '确定',
        type: 'warning' })
        .then(() => {
          const params = {}
          params[this.delIdKey] = row[this.delIdKey]
          return this.del(params)
        })
        .then(({ success, message }) => {
          this.$message({
            type: success ? 'success' : 'error',
            message: message
          })
          if (success) {
            this.$refs.table.load(1)
          }
          setTimeout(() => {
            document.activeElement.blur()
          }, 300)
        }).catch((error) => {
          setTimeout(() => {
            document.activeElement.blur()
          }, 300)
          this.$message({
            type: 'info',
            message: error === 'cancel' ? '已取消删除' : error
          })
          // return Promise.reject(error)
        })
    },
    handleCurrentChange() { },
    // 导入模型
    handleImport() {
      this.$refs.upload.$refs['upload-inner'].$refs.input.click()
    },
    // eslint-disble-next-line
    handleFileSuccess(response, file, fileList) {
      console.log(response, 'response')
      // this.imgUploaded = response
      // this.formPanel.setPrizeInfo.model.filePath = response.data.fileUrl
      // this.formPanel.setPrizeInfo.model.fileId = response.data.fileId
    },
    // eslint-disble-next-line
    handleFileError(err, file, fileList) {
      console.log(err)
    },
    handleHttpRequest() {
      const formData = new FormData()
      formData.append('file', this.file)
      return new Promise((resolve, reject) => {
        this.import(formData).then(({ success, message }) => {
          this.$message({
            type: success ? 'success' : 'error',
            message
          })
          this.$refs.upload.fileList && this.$refs.upload.fileList.splice(0)
          if (success) {
            this.$refs.table.load(1)
            resolve()
          } else {
            throw new Error(message)
          }
        })
        .catch(err => {
          this.$refs.upload.fileList && this.$refs.upload.fileList.splice(0)
          console.log(err)
          reject(err)
        })
      })
    },
    // eslint-disable-next-line
    handleFileChange(file, fileList) {
      this.file = file.raw
    },
    // eslint-disble-next-line
    renderCustom(h) {
      return (
        <c-upload
          class="upload-file"
          ref="upload"
          auto-upload={ true }
          action="/v1/activiti/models/importModel"
          accept={ this.acceptFileType }
          list-type="picture"
          name="file"
          limit={1}
          {
            ...{
              props: {
                onChange: this.handleFileChange,
                httpRequest: this.handleHttpRequest
                // onSuccess: this.handleFileSuccess,
                // onError: this.handleFileError
              }
            }
          }
        >
          <c-button size="small" ref="button" type="primary">点击上传</c-button>
        </c-upload>
      )
    }
  },
  beforeRouteEnter(to, from, next) {
    // 判断是否从绘制模型页跳转而来修复新增或编辑保存后，列表内容未更新问题
    const index = from.path.indexOf('/activiti/model/drawModel')
    if (index > -1) return next(vm => vm.$refs.table.load(1))
    next()
  },
  beforeCreate() {
    const urlArr = (this.$route.meta && this.$route.meta.children || []).map(item => item.url)

    this.toolPanelBtns =  [
      { label: '绘制流程', methods: 'handleAdd', url:'/v1/activiti/models/newModel', icon: 'el-icon-circle-plus-outline', type: 'primary', disabled: false },
      { label: '导入模型', methods: 'handleImport', url:'', svgIcon: 'import', type: 'import', disabled: false }
    ].filter(item => (item.url && urlArr.includes(item.url)) || !item.url)

    this.tableRowBtnList = [
      { label: '编辑', methods: 'handleEdit', url:'', icon: 'el-icon-edit-outline', type: 'primary', key: 'edit', align: 'top-start', disabled: false },
      { label: '导出', methods: 'handleExport', url:'/v1/activiti/models/export', svgIcon: 'modelExport', type: '', key: '', align: 'top-start', disabled: false },
      { label: '发布', methods: 'handleDeployment', url:'/v1/activiti/models/deployment', svgIcon: 'deployment', type: '', key: '', align: 'top-start', disabled: false },
      { label: '删除', methods: 'handleDelete', url:'/v1/activiti/models/delete', icon: 'el-icon-delete', type: 'danger', key: 'delete', align: 'top-start', disabled: false }
    ].filter(item => (item.url && urlArr.includes(item.url)) || !item.url)
  }
}
</script>

<style lang='scss'>
.model{
  box-sizing: border-box;
  .upload-file{
    display: none;
  }
}
</style>

